<template>
    <a-modal
        :after-close="onAfterClose"
        cancel-text="取消"
        ok-text="确认"
        :confirm-loading="modal.confirmLoading"
        :open="modal.open"
        :title="modal.title"
        :width="480"
        @cancel="handleCancel"
        @ok="handleOk">
        <ezForm
            ref="form"
            v-model:formValue="formData"
            :formItems="formItems" />
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import ezForm from '@/views/components/ezForm.vue'
import { onMounted, ref } from 'vue'

const emit = defineEmits(['ok'])
const { permissions, formItems } = defineProps({ permissions: {}, formItems: {} })
const { modal, openModal, closeModal, showLoading, hideLoading } = useModal()
const form = ref()
const { formRecord, formData } = useForm()
/**
 * 新建
 */
function handleCreate() {
    openModal({
        type: 'create',
        title: '新建用户',
    })
}
onMounted(() => {
    console.log(313213)
})
/**
 * 编辑
 */
function handleEdit(record = {}) {
    openModal({
        type: 'edit',
        title: '编辑用户',
    })
    formRecord.value = record
    formData.value = cloneDeep(record)
}

/**
 * 确定
 */
function handleOk() {
    form.value
        .validateFields()
        .then(async (values) => {
            console.log('values', values)
            try {
                showLoading()
                const params = {
                    id: formRecord.value.id,
                    ...values,
                }
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.message.create(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        result = await apis.system.update(params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === result?.code) {
                    closeModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}

/**
 * 取消
 */
function handleCancel() {
    closeModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    form.value.resetForm()
    hideLoading()
}

defineExpose({
    handleCreate,
    handleEdit,
})
</script>

<style lang="less" scoped></style>
